package com.pansoft.xbrl.xbrljson.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 获取类资源类型工具类
 * 
 * @author coolmayi
 *
 */
public class FiledUtil {

	
	/**
	 * 获取字段名称
	 * @param filedName
	 * @param classObject
	 * @return
	 */
	public static Object getFiledValue(String filedName, Object classObject) {

		if (filedName.indexOf("@") >= 0) {
			filedName = filedName.substring(1, filedName.length() - 1);
		}
		
		String[] filedNames = filedName.split("&");
		List<Object> retObjList = new ArrayList<Object>();
		try {
			for (String name : filedNames) {
				int pos = name.indexOf(".");
				Object filedObject = null;
				if (pos > 0) {
					// 需要获取子属性
					String childFiledName = name.substring(pos + 1, name.length());
					name = name.substring(0, pos);
					Field f = classObject.getClass().getField(name);
					if (f != null) {
						Object childObject = f.get(classObject);
						filedObject = FiledUtil.getFiledValue(childFiledName, childObject);
					}

				} else {
					Field f = null;
					f = classObject.getClass().getField(name);
					if (f != null) {
						filedObject = f.get(classObject);
					}
				}
				
				if (filedObject != null) {
					retObjList.add(filedObject);
				}
			}


		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		
		Object ret = null;
		
		if (retObjList.size() == 1) {
			ret = retObjList.get(0);
		}else if (retObjList.size() > 1) {
			ret = "";
			// 多字段拼接，认为是字符串处理
			for (Object object : retObjList) {
				ret += object.toString();
			}
		} 
		return ret;
	}
}
